import re
import requests
import json

# 导入进程模块
import subprocess

import os

url = 'https://www.bilibili.com/video/BV18a411i7eR'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36',
    'Referer': 'https://www.bilibili.com'
}
response = requests.get(url=url, headers=headers)
playinfo = re.findall('<script>window.__playinfo__=(.*?)</script>', response.text)[0]
json_data = json.loads(playinfo)
# print(json_data)
video_url = json_data['data']['dash']['video'][0]['baseUrl']
audio_url = json_data['data']['dash']['audio'][0]['baseUrl']
title = re.findall('<h1 id="video-title" title="(.*?)" class="video-title">', response.text)[0]
title = title.replace(r'|', '')
print('视频: ', video_url)
print('音频: ', audio_url)
print('标题: ', title)

video_content = requests.get(url=video_url, headers=headers).content
audio_content = requests.get(url=audio_url, headers=headers).content

with open(title + '.mp4', 'wb') as f:
    f.write(video_content)

with open(title + '.mp3', 'wb') as f:
    f.write(audio_content)

# 视频合并 ffmpeg 工具

'ffmpeg -i out.mp4 -i out.aac -vcodec copy -acodec copy new.mp4'
cmd = f"ffmpeg -i {title}.mp4 -i {title}.mp3 -c:v copy -c:a aac -strict experimental {title}output.mp4"

# cmd = f'ffmpeg -i {title}.mp4 -i  {title}.mp3 -vcodec copy -acodec copy {title}.mp4'

subprocess.run(cmd, shell=True)
# os.remove(f'{title}.mp4')
# os.remove(f'{title}.mp3')
print(title, '视频合成完毕!')
